package com.example.service;

import com.example.latch.DbLeaderLatch;
import com.example.latch.LeaderLatchListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

@Service
public class MasterServiceImpl implements MasterService, InitializingBean, DisposableBean, ApplicationContextAware {

    Logger logger = LoggerFactory.getLogger(getClass());

    private ApplicationContext applicationContext;

    private DbLeaderLatch dbLeaderLatch;

    @Override
    public void destroy() throws Exception {
        this.dbLeaderLatch.unlock();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.dbLeaderLatch = new DbLeaderLatch(this.applicationContext, new LeaderLatchListener() {
            @Override
            public void isMaster() {
                logger.warn("master node start ...");
                while (true){
                    try {
                        Thread.sleep(30000);
                    } catch (InterruptedException e) {
                    }
                }
            }
        });
        this.dbLeaderLatch.lock();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
